#pragma once
#include "Server.hpp"
#include <fstream>
#include <sys/stat.h>
#include <regex>

std::unordered_map<int, std::string> _statu_msg = {
	{100, "Continue"},
	{101, "Switching Protocol"},
	{102, "Processing"},
	{103, "Early Hints"},
	{200, "OK"},
	{201, "Created"},
	{202, "Accepted"},
	{203, "Non-Authoritative Information"},
	{204, "No Content"},
	{205, "Reset Content"},
	{206, "Partial Content"},
	{207, "Multi-Status"},
	{208, "Already Reported"},
	{226, "IM Used"},
	{300, "Multiple Choice"},
	{301, "Moved Permanently"},
	{302, "Found"},
	{303, "See Other"},
	{304, "Not Modified"},
	{305, "Use Proxy"},
	{306, "unused"},
	{307, "Temporary Redirect"},
	{308, "Permanent Redirect"},
	{400, "Bad Request"},
	{401, "Unauthorized"},
	{402, "Payment Required"},
	{403, "Forbidden"},
	{404, "Not Found"},
	{405, "Method Not Allowed"},
	{406, "Not Acceptable"},
	{407, "Proxy Authentication Required"},
	{408, "Request Timeout"},
	{409, "Conflict"},
	{410, "Gone"},
	{411, "Length Required"},
	{412, "Precondition Failed"},
	{413, "Payload Too Large"},
	{414, "URI Too Long"},
	{415, "Unsupported Media Type"},
	{416, "Range Not Satisfiable"},
	{417, "Expectation Failed"},
	{418, "I'm a teapot"},
	{421, "Misdirected Request"},
	{422, "Unprocessable Entity"},
	{423, "Locked"},
	{424, "Failed Dependency"},
	{425, "Too Early"},
	{426, "Upgrade Required"},
	{428, "Precondition Required"},
	{429, "Too Many Requests"},
	{431, "Request Header Fields Too Large"},
	{451, "Unavailable For Legal Reasons"},
	{501, "Not Implemented"},
	{502, "Bad Gateway"},
	{503, "Service Unavailable"},
	{504, "Gateway Timeout"},
	{505, "HTTP Version Not Supported"},
	{506, "Variant Also Negotiates"},
	{507, "Insufficient Storage"},
	{508, "Loop Detected"},
	{510, "Not Extended"},
	{511, "Network Authentication Required"}};

std::unordered_map<std::string, std::string> _mime_msg = {
	{".aac", "audio/aac"},
	{".abw", "application/x-abiword"},
	{".arc", "application/x-freearc"},
	{".avi", "video/x-msvideo"},
	{".azw", "application/vnd.amazon.ebook"},
	{".bin", "application/octet-stream"},
	{".bmp", "image/bmp"},
	{".bz", "application/x-bzip"},
	{".bz2", "application/x-bzip2"},
	{".csh", "application/x-csh"},
	{".css", "text/css"},
	{".csv", "text/csv"},
	{".doc", "application/msword"},
	{".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
	{".eot", "application/vnd.ms-fontobject"},
	{".epub", "application/epub+zip"},
	{".gif", "image/gif"},
	{".htm", "text/html"},
	{".html", "text/html"},
	{".ico", "image/vnd.microsoft.icon"},
	{".ics", "text/calendar"},
	{".jar", "application/java-archive"},
	{".jpeg", "image/jpeg"},
	{".jpg", "image/jpeg"},
	{".js", "text/javascript"},
	{".json", "application/json"},
	{".jsonld", "application/ld+json"},
	{".mid", "audio/midi"},
	{".midi", "audio/x-midi"},
	{".mjs", "text/javascript"},
	{".mp3", "audio/mpeg"},
	{".mpeg", "video/mpeg"},
	{".mpkg", "application/vnd.apple.installer+xml"},
	{".odp", "application/vnd.oasis.opendocument.presentation"},
	{".ods", "application/vnd.oasis.opendocument.spreadsheet"},
	{".odt", "application/vnd.oasis.opendocument.text"},
	{".oga", "audio/ogg"},
	{".ogv", "video/ogg"},
	{".ogx", "application/ogg"},
	{".otf", "font/otf"},
	{".png", "image/png"},
	{".pdf", "application/pdf"},
	{".ppt", "application/vnd.ms-powerpoint"},
	{".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
	{".rar", "application/x-rar-compressed"},
	{".rtf", "application/rtf"},
	{".sh", "application/x-sh"},
	{".svg", "image/svg+xml"},
	{".swf", "application/x-shockwave-flash"},
	{".tar", "application/x-tar"},
	{".tif", "image/tiff"},
	{".tiff", "image/tiff"},
	{".ttf", "font/ttf"},
	{".txt", "text/plain"},
	{".vsd", "application/vnd.visio"},
	{".wav", "audio/wav"},
	{".weba", "audio/webm"},
	{".webm", "video/webm"},
	{".webp", "image/webp"},
	{".woff", "font/woff"},
	{".woff2", "font/woff2"},
	{".xhtml", "application/xhtml+xml"},
	{".xls", "application/vnd.ms-excel"},
	{".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
	{".xml", "application/xml"},
	{".xul", "application/vnd.mozilla.xul+xml"},
	{".zip", "application/zip"},
	{".3gp", "video/3gpp"},
	{".3g2", "video/3gpp2"},
	{".7z", "application/x-7z-compressed"}};

class Util
{
public:
	// 字符串分割函数,将src字符串按照sep字符进行分割，得到的各个字串放到arry中，最终返回字串的数量
	static size_t Split(const std::string &src, const std::string &sep, std::vector<std::string> *arry)
	{
		// aa,bb,cc,
		int offset = 0;
		while (offset < src.size())
		{
			size_t pos = src.find(sep, offset);
			if (pos == std::string::npos)
			{
				// 没有找到，就说明都是字串
				arry->push_back(src.substr(offset));
				break;
			}
			if (pos == offset)
			{
				offset = pos + sep.size();
				continue;
			}
			arry->push_back(src.substr(offset, pos - offset));
			offset = pos + sep.size();
		}
		return arry->size();
	}
	// 读取文件内容
	static bool ReadFile(const std::string &filename, std::string *buff)
	{
		// 对文件进行二进制操作
		std::ifstream ifs(filename, std::ios::binary);
		if (ifs.is_open() == false) // 打开文件
		{
			DEL_LOG("open filename error : %s", filename.c_str());
			return false;
		}
		size_t ret = 0;
		ifs.seekg(0, ifs.end); // 跳转读写位置到末尾
		ret = ifs.tellg();	   // 获取当前读写位置相对于起始位置的偏移量，从末尾偏移刚好就是文件大小
		ifs.seekg(0, ifs.beg); // 跳转到起始位置
		buff->resize(ret);
		ifs.read(&(*buff)[0], ret);
		if (ifs.good() == false) // 判断是否读取成功
		{
			DEL_LOG("read filename error : %s", filename.c_str());
			ifs.close();
			return false;
		}
		ifs.close();
		return true;
	}
	// 向文件写入数据
	static bool WriteFile(std::string &filename, const std::string &buff)
	{
		std::ofstream ofs(filename, std::ios::binary | std::ios::trunc);
		if (ofs.is_open() == false) // 打开文件
		{
			DEL_LOG("open filename error : %s", filename.c_str());
			return false;
		}
		ofs.write(buff.c_str(), buff.size());
		if (ofs.good() == false) // 判断上一步是否成功
		{
			DEL_LOG("write filename error : %s", filename.c_str());
			ofs.close();
			return false;
		}
		ofs.close();
		return true;
	}
	// URL编码，避免URL中资源路径与查询字符串中的特殊字符与HTTP请求中特殊字符产生歧义
	// 编码格式：将特殊字符的ascii值，转换为两个16进制字符，前缀%   C++ -> C%2B%2B
	//   不编码的特殊字符： RFC3986文档规定 . - _ ~ 字母，数字属于绝对不编码字符
	// RFC3986文档规定，编码格式 %HH
	// W3C标准中规定，查询字符串中的空格，需要编码为+， 解码则是+转空格
	// URL编码
	static std::string URLEncode(const std::string &url, bool convert_space_to_plus)
	{
		std::string res;
		for (auto &e : url)
		{
			if (e == '.' || e == '-' || e == '_' || e == '~')
			{
				res += e;
				continue;
			}
			if (e == ' ' && convert_space_to_plus)
			{
				res += '+';
				continue;
			}
			// 剩下的字符都是需要编码成为 %HH 格式
			char tmp[4];
			snprintf(tmp, 4, "%%%02X", e);
			res += tmp;
		}
		return res;
	}
	static char HexToi(char c)
	{
		if (c >= '0' && c <= '9')
		{
			return c - '0';
		}
		else if (c >= 'a' && c <= 'z')
		{
			return c - 'a' + 10;
		}
		else if (c >= 'A' && c <= 'Z')
		{
			return c - 'A' + 10;
		}
		return -1;
	}
	// URL解码
	static std::string URLDecode(const std::string &url, bool convert_space_to_plus)
	{
		std::string res;
		// 遇到了%，则将紧随其后的2个字符，转换为数字，第一个数字左移4位，然后加上第二个数字  + -> 2b  %2b->2 << 4 + 11
		for (int i = 0; i < url.size(); i++)
		{
			if (url[i] == '+' && convert_space_to_plus)
			{
				res += ' ';
				continue;
			}
			if (url[i] == '%')
			{
				char v1 = HexToi(url[i + 1]);
				char v2 = HexToi(url[i + 2]);
				char v = (v1 << 4) + v2;
				res += v;
				i += 2;
				continue;
			}
			res += url[i];
		}
		return res;
	}
	// 响应状态码的描述信息获取
	static std::string StateDesc(int state)
	{
		auto it = _statu_msg.find(state);
		if (it == _statu_msg.end())
		{
			return "Unknow";
		}
		return it->second;
	}
	// 根据文件后缀获取文件mine
	static std::string ExtMine(const std::string &filename)
	{
		size_t pos = filename.find_last_of('.');
		if (pos == std::string::npos)
		{
			return "application/octet-stream";
		}
		std::string str = filename.substr(pos);
		auto it = _mime_msg.find(str);
		if (it == _mime_msg.end())
		{
			return "application/octet-stream";
		}
		return it->second;
	}
	// 判断文件是否是一个目录文件
	static bool IsDirectory(const std::string &filename)
	{
		struct stat st;
		int ret = stat(filename.c_str(), &st);
		if (ret < 0)
		{
			return false;
		}
		return S_ISDIR(st.st_mode);
	}
	// 判断文件是否是一个普通文件
	static bool IsOrdinaryFile(const std::string &filename)
	{
		struct stat st;
		int ret = stat(filename.c_str(), &st);
		if (ret < 0)
		{
			return false;
		}
		return S_ISREG(st.st_mode);
	}
	// http请求的资源路径有效性判断
	//  /index.html  --- 前边的/叫做相对根目录  映射的是某个服务器上的子目录
	//  想表达的意思就是，客户端只能请求相对根目录中的资源，其他地方的资源都不予理会
	//  /../login, 这个路径中的..会让路径的查找跑到相对根目录之外，这是不合理的，不安全的
	// http请求资源路径的有效性
	static bool ValidPath(const std::string &path)
	{
		int val = 0;
		std::string sep = "/";
		std::vector<std::string> arry;
		Split(path, sep, &arry);
		for (const auto &e : arry)
		{
			if (e == "..")
			{
				val--;
				if (val < 0)
				{
					return false;
				}
				continue;
			}
			val++;
		}
		return true;
	}
};

class HttpRequest
{

public:
	std::string _method;								   // 请求方法
	std::string _path;									   // 资源路径
	std::string _version;								   // 协议版本
	std::string _body;									   // 请求正文
	std::smatch _matchs;								   // 资源路径的正则提取数据
	std::unordered_map<std::string, std::string> _headers; // 头部字段
	std::unordered_map<std::string, std::string> _params;  // 查询字符串
public:
	HttpRequest()
		: _version("HTTP/1.1")
	{
	}
	void ReSet()
	{
		_method.clear();
		_path.clear();
		_version = "HTTP/1.1";
		_body.clear();
		std::smatch ch;
		_matchs.swap(ch);
		_headers.clear();
		_params.clear();
	}
	// 设置头部字段
	void SetHeader(const std::string &key, const std::string &val)
	{
		_headers.insert(std::make_pair(key, val));
	}
	// 是否存在指定头部字段
	bool HasHeader(const std::string &key)
	{
		auto it = _headers.find(key);
		if (it != _headers.end())
		{
			return true;
		}
		return false;
	}
	// 获取指定头部字段
	std::string GetHeader(const std::string &key)
	{
		bool ret = HasHeader(key);
		if (ret == false)
		{
			return "";
		}
		auto it = _headers.find(key);
		return it->second;
	}
	// 设置查询字符串
	void SetParam(const std::string &key, const std::string &val)
	{
		_params.insert(std::make_pair(key, val));
	}
	// 是否存在指定查询字符串
	bool HasParam(const std::string &key)
	{
		auto it = _params.find(key);
		if (it != _params.end())
		{
			return true;
		}
		return false;
	}
	// 获取指定查询字符串
	std::string GetParam(const std::string &key)
	{
		bool ret = HasParam(key);
		if (ret == false)
		{
			return "";
		}
		auto it = _params.find(key);
		return it->second;
	}
	// 获取正文长度
	size_t ContentLength()
	{
		// Content-Length: 1234\r\n
		bool ret = HasHeader("Content-Length"); // Content-Length
		if (ret == false)
		{
			return 0;
		}
		std::string cl = GetHeader("Content-Length");
		return std::stol(cl);
	}
	// 判断是否为短链接
	bool Close()
	{
		// 没有Connection字段，或者有Connection但是值是close，则都是短链接，否则就是长连接
		if (HasHeader("Connection") == true && GetHeader("Connection") == "keep-alive")
		{
			return false;
		}
		return true;
	}
};

class HttpResponse
{
public:
	HttpResponse()
		: _redirect_flag(false), _state(200)
	{
	}
	HttpResponse(int state)
		: _redirect_flag(false), _state(state)
	{
	}
	void ReSet()
	{
		_state = 200;
		_redirect_flag = false;
		_redirect_url.clear();
		_body.clear();
		_headers.clear();
	}
	// 设置头部字段
	void SetHeader(const std::string &key, const std::string &val)
	{
		_headers.insert(std::make_pair(key, val));
	}
	// 是否存在指定头部字段
	bool HasHeader(const std::string &key)
	{
		auto it = _headers.find(key);
		if (it != _headers.end())
		{
			return true;
		}
		return false;
	}
	// 获取指定头部字段
	std::string GetHeader(const std::string &key)
	{
		bool ret = HasHeader(key);
		if (ret == false)
		{
			return "";
		}
		auto it = _headers.find(key);
		return it->second;
	}
	// 设置正文
	void SetContent(const std::string &body, const std::string &type = "text/html")
	{
		_body = body;
		SetHeader("Content-Type", type);
	}
	// 设置重定向
	void SetRedirect(const std::string &url, int state = 302)
	{
		_redirect_url = url;
		_state = state;
		_redirect_flag = true;
	}
	// 判断是否为短链接
	bool Close()
	{
		// 没有Connection字段，或者有Connection但是值是close，则都是短链接，否则就是长连接
		if (HasHeader("Connection") == true && GetHeader("Connection") == "keep-alive")
		{
			return false;
		}
		return true;
	}

public:
	int _state;											   // 响应状态码
	bool _redirect_flag;								   // 是否重定向
	std::string _redirect_url;							   // 重定向路径
	std::string _body;									   // 正文
	std::unordered_map<std::string, std::string> _headers; // 保存头部字段
};

typedef enum
{
	HTTP_RECV_ERROR,
	HTTP_RECV_LINE,
	HTTP_RECV_HEAD,
	HTTP_RECV_BODY,
	HTTP_RECV_OVER,
} HttpRecvState;
#define MAX_LINE 8192 // 8kb
class HttpContext
{
private:
	// 解析请求行
	bool ParesHttpLine(const std::string &line)
	{
		std::smatch re;
		std::regex e("(GET|POST|PUT|DELETE|HEAD) ([^?]*)(?:\\?(.*))? (HTTP/\\d+\\.\\d+)(?:\r|\n|\r\n)?", std::regex::icase);
		bool ret = std::regex_match(line, re, e);
		if (ret == false)
		{
			_recv_state = HTTP_RECV_ERROR;
			_resp_state = 400; // Bad Request
			return false;
		}
		// 0 : GET /xiazelin/login?user=lixj&pass=1234 HTTP/1.0

		// 1 : GET
		// 2 : /xiazelin/login
		// 3 : user=lixj&pass=1234
		// 4 : HTTP/1.0
		_request._method = re[1];
		std::transform(_request._method.begin(), _request._method.end(), _request._method.begin(), ::toupper);
		_request._path = Util::URLDecode(re[2], false); // 资源路径会被编码，所以要解密,不需要把+编成空格
		_request._version = re[4];
		std::string src = re[3];
		std::vector<std::string> recv_arry;
		Util::Split(src, "&", &recv_arry);
		for (auto &e : recv_arry)
		{
			size_t pos = e.find("=");
			if (pos == std::string::npos)
			{
				_resp_state = 400;
				_recv_state = HTTP_RECV_ERROR;
				return false;
			}
			std::string key = Util::URLDecode(e.substr(0, pos), true);
			std::string val = Util::URLDecode(e.substr(pos + 1), true);
			_request.SetParam(key, val);
		};
		return true;
	}
	// 读取请求行
	bool RecvHttpLine(Buffer *buff)
	{
		if (_recv_state != HTTP_RECV_LINE)
		{
			return false;
		}
		std::string line = buff->GetLineBufferAndPop();
		// 如果读取为空，则说明不足一行数据，但如果一行数据太大，超过一定限度则不合规
		if (line.size() == 0)
		{
			if (buff->ReadableSize() > MAX_LINE)
			{
				_resp_state = 414; // URI TOO LONG
				_recv_state = HTTP_RECV_ERROR;
				return false;
			}
			// 等下一行数据到来
			return true;
		}
		// 如果读取的一行数据超过8kb那么也不合规
		if (line.size() > MAX_LINE)
		{
			_resp_state = 414; // URI TOO LONG
			_recv_state = HTTP_RECV_ERROR;
			return false;
		}
		bool ret = ParesHttpLine(line);
		if (ret == false)
		{
			return false;
		}
		_recv_state = HTTP_RECV_HEAD;
		return true;
	}
	// 解析请求头部信息
	bool ParesHttpHead(std::string &line)
	{
		if (line.back() == '\n')
		{
			line.pop_back(); // 末尾是换行则去掉换行字符
		}
		if (line.back() == '\r')
		{
			line.pop_back(); // 末尾是回车则去掉回车字符
		}
		size_t pos = line.find(": ");
		if (pos == std::string::npos)
		{
			_recv_state = HTTP_RECV_ERROR;
			_resp_state = 400;
			return false;
		}
		std::string key = Util::URLDecode(line.substr(0, pos), true);
		std::string val = Util::URLDecode(line.substr(pos + 2), true);
		_request.SetHeader(key, val);
		return true;
	}
	// 读取请求头部信息
	bool RecvHttpHead(Buffer *buff)
	{
		if (_recv_state != HTTP_RECV_HEAD)
		{
			return false;
		}
		// //一行一行取出数据，直到遇到空行为止， 头部的格式 key: val\r\nkey: val\r\n....
		while (1)
		{
			std::string line = buff->GetLineBufferAndPop();
			// 如果读取为空，则说明不足一行数据，但如果一行数据太大，超过一定限度则不合规
			if (line.size() == 0)
			{
				if (buff->ReadableSize() >= MAX_LINE)
				{
					_resp_state = 414; // URI TOO LONG
					_recv_state = HTTP_RECV_ERROR;
					return false;
				}
				// 等下一行数据到来
				return true;
			}
			// 如果读取的一行数据超过8kb那么也不合规
			if (line.size() > MAX_LINE)
			{
				_resp_state = 414; // URI TOO LONG
				_recv_state = HTTP_RECV_ERROR;
				return false;
			}
			if (line == "\n" || line == "\r\n")
			{
				break;
			}
			bool ret = ParesHttpHead(line);
			if (ret == false)
			{
				return false;
			}
		}
		_recv_state = HTTP_RECV_BODY;
		return true;
	}
	// 读取正文
	bool RecvHttpBody(Buffer *buff)
	{
		if (_recv_state != HTTP_RECV_BODY)
		{
			return false;
		}
		// 获取正文长度
		int content_length = _request.ContentLength();
		if (content_length == 0)
		{
			// 没有正文，则获取完毕
			_recv_state = HTTP_RECV_OVER;
			return true;
		}
		// 获取当前正文长度，如果当前正文长度小于获取的正文长度，则说明还要正文没有获取，
		// 当前正文长度，就是往多少_request.body放了多少数据后还需要放多少数据
		int real_len = content_length - _request._body.size(); // 还需要放入的实际长度
															   // 3. 接收正文放到body中，但是也要考虑当前缓冲区中的数据，是否是全部的正文

		//  3.1 缓冲区中数据，包含了当前请求的所有正文，则取出所需的数据
		if (buff->ReadableSize() >= real_len)
		{
			_request._body.append(buff->ReadPosition(), real_len);
			buff->MoveReadOffset(real_len); // 写成了写偏移往后移动，就会造成可读数据没有取出，
											// 重置上下文后，又会有原本的一行数据，然后请求行数据过大，导致错误
			_recv_state = HTTP_RECV_OVER;
			return true;
		}
		// 说明buff里面数据数据不足，等待下次新数据到来
		_request._body.append(buff->ReadPosition(), buff->ReadableSize());
		buff->MoveReadOffset(buff->ReadableSize());
		return true;
	}

public:
	HttpContext()
		: _resp_state(200), _recv_state(HTTP_RECV_LINE)
	{
	}
	void ReSet()
	{
		_resp_state = 200;
		_recv_state = HTTP_RECV_LINE;
		_request.ReSet();
	}
	int RespState()
	{
		return _resp_state;
	}
	HttpRecvState RecvState()
	{
		return _recv_state;
	}
	HttpRequest &Request()
	{
		return _request;
	}
	// 接收并解析HTTP请求
	void RecvHttpRequest(Buffer *buff)
	{
		// 不同的状态，做不同的事情，但是这里不要break， 因为处理完请求行后，应该立即处理头部，而不是退出等新数据
		switch (_recv_state)
		{
		case HTTP_RECV_LINE:
			RecvHttpLine(buff);
		case HTTP_RECV_HEAD:
			RecvHttpHead(buff);
		case HTTP_RECV_BODY:
			RecvHttpBody(buff);
		}
		return;
	}

private:
	int _resp_state;		   // 响应状态码
	HttpRecvState _recv_state; // 阶段状态
	HttpRequest _request;	   // 已经解析完毕的请求信息
};

using Header = std::function<void(HttpRequest &req, HttpResponse *resp)>;
using Headers = std::vector<std::pair<std::regex, Header>>;
#define DEFALT_TIMEOUT 30
class HttpServer
{
private:
	// 将响应信息进行发送
	void WriteResponse(const Ptrconnection &con, HttpRequest &req, HttpResponse *resp)
	{
		// 先完善头部字段
		if (req.Close() == true)
		{
			resp->SetHeader("Connection", "close");
		}
		else
		{
			resp->SetHeader("Connection", "keep-alive");
		}
		// 如果正文不为空 &&
		if (resp->_body.empty() == false && resp->HasHeader("Content-Length") == false)
		{
			resp->SetHeader("Content-Length", std::to_string(resp->_body.size()));
		}
		if (resp->_body.empty() == false && resp->HasHeader("Content-Type") == false)
		{
			resp->SetHeader("Content-Type", "application/octet-stream");
		}
		if (resp->_redirect_flag == true)
		{
			resp->SetHeader("Location", resp->_redirect_url);
		}
		// 2. 将rsp中的要素，按照http协议格式进行组织
		// HTTP-Version Status-Code Reason-Phrase\r\n
		// Headers\r\n
		// \r\n
		// Message-Body
		std::stringstream str;
		str << req._version << " " << std::to_string(resp->_state) << " " << Util::StateDesc(resp->_state) << "\r\n";
		for (auto &head : resp->_headers)
		{
			str << head.first << ": " << head.second << "\r\n";
		}
		str << "\r\n";
		str << resp->_body;
		con->Send(str.str().c_str(), str.str().size());
	}
	void ErrorHandler(HttpRequest &req, HttpResponse *resp)
	{
		std::string body;
		body += "<html>";
		body += "<head>";
		body += "<meta http-equiv='Content-Type' content='text/html;charset=utf-8'>";
		body += "</head>";
		body += "<body>";
		body += "<h1>";
		body += std::to_string(resp->_state);
		body += " ";
		body += Util::StateDesc(resp->_state);
		body += "</h1>";
		body += "</body>";
		body += "</html>";
		// 2. 将页面数据，当作响应正文，放入rsp中
		resp->SetContent(body, "text/html");
		// std::string body;
		// std::string filename = "../wwwroot/404.html";
		// Util::ReadFile(filename, &body);
		// resp->SetContent(body, "text.html");
	}
	// 是否是静态资源请求
	bool IsStaticHandler(const HttpRequest &req)
	{
		// 1. 必须设置了静态资源根目录
		if (_base_dir.empty())
		{
			return false;
		}
		// 2. 请求方法，必须是GET / HEAD请求方法
		if (req._method != "GET" && req._method != "HEAD")
		{
			return false;
		}
		// 3. 请求的资源路径必须是一个合法路径
		if (!Util::ValidPath(req._path))
		{
			return false;
		}
		// 4. 请求的资源必须存在,且是一个普通文件
		//    有一种请求比较特殊 -- 目录：/, /image/， 这种情况给后边默认追加一个 index.html
		// index.html    /image/a.png
		// 不要忘了前缀的相对根目录,也就是将请求路径转换为实际存在的路径  /image/a.png  ->   ./wwwroot/image/a.png
		std::string req_path = _base_dir + req._path;
		if (req._path.back() == '/')
		{
			req_path += "index.html";
		}
		if (!Util::IsOrdinaryFile(req_path))
		{
			return false;
		}
		return true;
	}
	// 静态资源请求--- 将静态资源文件的数据读取出来，放到rsp的_body中, 并设置mime
	void StaticHeader(HttpRequest &req, HttpResponse *resp)
	{
		std::string req_path = _base_dir + req._path;
		if (req._path.back() == '/')
		{
			req_path += "index.html";
		}
		bool ret = Util::ReadFile(req_path, &resp->_body);
		if (ret == false)
		{
			return;
		}
		std::string mime = Util::ExtMine(req_path);
		resp->SetHeader("Content-Type", mime);
		return;
	}
	// 功能性请求的分类处理,资源调度
	void Dispatcher(HttpRequest &req, HttpResponse *resp, Headers &headers)
	{
		// 在对应请求方法的路由表中，查找是否含有对应资源请求的处理函数，有则调用，没有则发挥404
		// 思想：路由表存储的时键值对 -- 正则表达式 & 处理函数
		// 使用正则表达式，对请求的资源路径进行正则匹配，匹配成功就使用对应函数进行处理
		//   /numbers/(\d+)       /numbers/12345
		for (auto &e : headers)
		{
			const std::regex &re = e.first;
			const Header &header = e.second;
			bool ret = std::regex_match(req._path, req._matchs, re);
			if (ret == false)
			{
				continue;
			}
			return header(req, resp);
		}
		resp->_state = 404;
	}
	// 进行方法路由
	void Route(HttpRequest &req, HttpResponse *resp)
	{
		if (IsStaticHandler(req) == true)
		{
			return StaticHeader(req, resp);
		}
		if (req._method == "GET" || req._method == "HEAD")
		{
			return Dispatcher(req, resp, _get_reout);
		}
		if (req._method == "PUT")
		{
			return Dispatcher(req, resp, _put_reout);
		}
		if (req._method == "POST")
		{
			return Dispatcher(req, resp, _post_reout);
		}
		if (req._method == "DELETE")
		{
			return Dispatcher(req, resp, _delete_reout);
		}
		resp->_state = 405;
		return;
	}
	// 设置上下文
	void SetContext(const Ptrconnection &con)
	{
		con->SetContext(HttpContext());
		INF_LOG("NEW CONNECTION %p", con.get());
	}
	// 缓冲区数据处理解析
	void OnMessage(const Ptrconnection &con, Buffer *buff)
	{
		while (true)
		{
			// 获取上下文进行
			HttpContext *context = con->GetContext()->get<HttpContext>();
			// 通过上下文，对缓冲区数据进行解析处理
			context->RecvHttpRequest(buff);
			HttpRequest &req = context->Request();
			HttpResponse resp(context->RespState());
			// 如果解析出错
			if (context->RespState() >= 400)
			{
				// 出现错误，就要返回一个错误的响应信息
				ErrorHandler(req, &resp); ////填充一个错误显示页面数据到rsp中
				// 进行发送
				WriteResponse(con, req, &resp);
				context->ReSet();
				buff->MoveReadOffset(buff->ReadableSize());
				con->Shutdown();
				return;
			}
			// 如果不为HTTP_RECV_OVER则等待下一次数据到来
			if (context->RecvState() != HTTP_RECV_OVER)
			{
				return;
			}
			// 请求路由，进行业务处理
			Route(req, &resp);
			// 发送响应
			WriteResponse(con, req, &resp);
			// 重置上下文
			context->ReSet();
			// 判断是否是短链接
			if (resp.Close() == true) // req.Close() == true 如果是这个内容被重置了所以会被判定为短链接直接断开
			{
				con->Shutdown();
			}
		}
	}

public:
	HttpServer(int port, int timeout = DEFALT_TIMEOUT)
		: _tcpserver(port)
	{
		_tcpserver.EnableInactiveRelease(timeout);
		_tcpserver.SetConnectCallback(std::bind(&HttpServer::SetContext, this, std::placeholders::_1));
		_tcpserver.SetMessageCallback(std::bind(&HttpServer::OnMessage, this, std::placeholders::_1, std::placeholders::_2));
	}
	void SetBaseDir(const std::string path)
	{
		assert(Util::IsDirectory(path) == true);
		_base_dir = path;
	}
	void SetGet(const std::string &pattern, const Header &header)
	{
		_get_reout.push_back(std::make_pair(std::regex(pattern), header));
	}
	void SetPut(const std::string &pattern, const Header &header)
	{
		_put_reout.push_back(std::make_pair(std::regex(pattern), header));
	}
	void SetPost(const std::string &pattern, const Header &header)
	{
		_post_reout.push_back(std::make_pair(std::regex(pattern), header));
	}
	void SetDelete(const std::string &pattern, const Header &header)
	{
		_delete_reout.push_back(std::make_pair(std::regex(pattern), header));
	}
	void SetThreadCount(int count)
	{
		_tcpserver.SetThreadCount(count);
	}
	void Listen()
	{
		_tcpserver.Start();
	}

private:
	Headers _get_reout;
	Headers _put_reout;
	Headers _post_reout;
	Headers _delete_reout;
	std::string _base_dir;
	TcpServer _tcpserver;
};